package com.lyon.custom.core.refresh;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.lyon.custom.config.LyonConfigProperties;
import com.lyon.custom.core.AbstractChangeShareListener;
import com.lyon.custom.core.ConfigService;
import com.lyon.custom.core.LyonConfigManager;
import com.lyon.custom.core.store.LyonPropertySourceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.PropertySource;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author LeeYan9
 * @since 2021-12-02
 */
@Slf4j
public class LyonConfigAutoRefresh implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {


    private ConfigService configService;
    private LyonConfigProperties configProperties;
    private ApplicationContext ac;
    private AtomicBoolean ready = new AtomicBoolean(false);

    public LyonConfigAutoRefresh(LyonConfigManager lyonConfigManager) {
        this.configService = lyonConfigManager.getConfigService();
        this.configProperties = lyonConfigManager.getConfigProperties();
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (ready.compareAndSet(false, true)) {
            registerConfigChangeListener();
        }
    }

    private void registerConfigChangeListener() {
        if (!configProperties.isRefresh()) {
            return;
        }
        Map<String, PropertySource<?>> propertySourceMap = LyonPropertySourceRepository.all();
        Iterator<String> iterator = propertySourceMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            List<String> split = CharSequenceUtil.split(key, ';');
            configService.addListener(split.get(0), split.get(1), new AbstractChangeShareListener() {
                @Override
                public void innerReceive(String group, String dataId, String fileExt, String content) {
                    ac.publishEvent(new RefreshEvent(this, null, "Lyon-Config-Refresh"));
                    log.info("刷新配置.. {}:{}:{}", dataId, group, fileExt);
                }
            });
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        this.ac = ac;
    }
}
